﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace AutoMap
{
    /// <summary>
    /// 表达式映射，缓存为字典
    /// </summary>
    public class ExpressionDictionaryMapper
    {
        private static Dictionary<string, object> dictionaries = new();

        public static TResult Map<T, TResult>(T entity) where TResult : new()
        {
            string key = $"{typeof(T).FullName}_{typeof(TResult).FullName}";
            if (!dictionaries.ContainsKey(key))
            {
                ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "m");
                var targettype = typeof(TResult);
                List<MemberBinding> memberBindings = new();
                foreach (var property in typeof(T).GetProperties())
                {
                    var memberExpression = Expression.Property(parameterExpression, property.Name);
                    var targetProperty = targettype.GetProperty(property.Name);
                    if (targetProperty == null) continue;
                    var memberBinding = Expression.Bind(targetProperty, memberExpression);
                    memberBindings.Add(memberBinding);
                }

                var resultExpression = Expression.New(typeof(TResult));
                var memberInit = Expression.MemberInit(resultExpression, memberBindings);
                var lambdaExpression = Expression.Lambda<Func<T, TResult>>(memberInit, parameterExpression);
                var func = lambdaExpression.Compile();
                dictionaries.Add(key, func);
                return func(entity);
            }
            else
            {
                var func = dictionaries[key] as Func<T, TResult>;
                return func == null ? new TResult() : func(entity);
            }
        }
    }
}
